package com.sky.task;



import com.sky.mapper.user.UserOrderMapper;
import com.sky.pojo.Orders;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.exception.ServiceException;
/*import com.wechat.pay.java.service.partnerpayments.nativepay.NativePayService;*/
import com.wechat.pay.java.service.payments.nativepay.NativePayService;
import com.wechat.pay.java.service.payments.nativepay.model.QueryOrderByOutTradeNoRequest;

import com.wechat.pay.java.service.payments.model.Transaction;
/*import com.wechat.pay.java.service.payments.nativepay.model.Transaction;*/
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;



import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class PayNotify {

    @Autowired
    private UserOrderMapper orderMapper;


    @Scheduled(cron = "0 0/1 * * * ?")
    public void checkOrderPayStatus(){
        log.info("检查支付超时订单任务");
        long start = System.currentTimeMillis();
        LocalDateTime before15min = LocalDateTime.now().minusMinutes(15);
        List<Orders> orders = orderMapper.selectOrderBytime(before15min);
        if (CollectionUtils.isEmpty(orders)){
            log.info("没有需要处理的订单");
            return;
        }
        for (Orders order : orders) {
            Boolean flag = getPayStatusFromWx(order.getNumber());
            if(flag){
                order.setStatus(Orders.TO_BE_CONFIRMED);
                order.setPayStatus(Orders.PAID);
                orderMapper.updateOrderPaySuccess(order);
            }else {
                order.setStatus((Orders.CANCELLED_ORDER));
                order.setCancelTime(LocalDateTime.now());
                order.setCancelReason("订单支付超时");
                orderMapper.cancelOrder(order);
            }
            long end = System.currentTimeMillis();
            log.info("检查支付超时任务完成，耗时：{}",(end-start)/1000);
        }


    }
    @Autowired
    private Config config;
    public Boolean getPayStatusFromWx(String orderNo){
        try{
            QueryOrderByOutTradeNoRequest request = new QueryOrderByOutTradeNoRequest();
            request.setMchid("1561414331");
            request.setOutTradeNo(orderNo);

            NativePayService payService = new NativePayService.Builder().config(config).build();
            com.wechat.pay.java.service.payments.model.Transaction transaction = payService.queryOrderByOutTradeNo(request);

            log.info("调用微信查询接口返回：{}",transaction);
            if (transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)){
                return true;
            }
        }catch (ServiceException e){
            if(e.getErrorCode().equals("ORDER_NOT_EXIST")){
                log.info("微信订单不存在，没有发起过支付");

            }
        }
        return false;

    }


}
